import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:qilo/core/constants/app_icons.dart';
import '../../../core/models/hot_item.dart';
import '../../../core/providers/hot_item_provider.dart';
import '../../../core/providers/global_state_coordinator.dart';
import '../../community/pages/community_detail_page.dart';

enum UserContentType { releases, favorites }

class UserContentGrid extends StatelessWidget {
  final UserContentType contentType;

  const UserContentGrid({super.key, required this.contentType});

  @override
  Widget build(BuildContext context) {
    return Consumer2<HotItemProvider, GlobalStateCoordinator>(
      builder: (context, hotItemProvider, coordinator, child) {
        final currentUser = coordinator.currentUser;
        if (currentUser == null) {
          return _buildEmptyState();
        }

        final items =
            contentType == UserContentType.releases
                ? hotItemProvider.getUserPublishedItems(currentUser.id)
                : hotItemProvider.getUserFavoriteItems(currentUser.id);

        if (items.isEmpty) {
          return _buildEmptyState();
        }

        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 0.w),
          child: GridView.builder(
            padding: EdgeInsets.only(bottom: 100.h, top: 10.h),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              crossAxisSpacing: 0.w,
              mainAxisSpacing: 0.h,
              childAspectRatio: 0.85,
            ),
            itemCount: items.length,
            itemBuilder: (context, index) {
              final item = items[index];
              return _buildGridItem(context, item);
            },
          ),
        );
      },
    );
  }

  Widget _buildGridItem(BuildContext context, HotItem item) {
    return GestureDetector(
      onTap: () => _handleItemTap(context, item),
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/card-bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        padding: EdgeInsets.only(
          left: 20.w,
          right: 20.w,
          top: 20.h,
          bottom: 30.h,
        ),
        child: Stack(
          fit: StackFit.expand,
          children: [
            Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: _getImageProvider(item.displayImageUrl),
                  fit: BoxFit.cover,
                ),
              ),
            ),

            Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.transparent,
                    Colors.black.withValues(alpha: 0.7),
                  ],
                ),
              ),
            ),

            if (!item.isImage)
              Center(
                child: Icon(
                  MyIcons.iconPlayFill,
                  size: 22.w,
                  color: Colors.white,
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 处理项目点击
  void _handleItemTap(BuildContext context, HotItem item) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => CommunityDetailPage(item: item)),
    );
  }

  /// 获取图片提供者
  ImageProvider _getImageProvider(String imageUrl) {
    if (imageUrl.startsWith('http')) {
      return NetworkImage(imageUrl);
    } else if (imageUrl.startsWith('assets/')) {
      return AssetImage(imageUrl);
    } else {
      // 假设是本地文件路径
      return FileImage(File(imageUrl));
    }
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    final isReleases = contentType == UserContentType.releases;

    return Builder(
      builder: (context) {
        return SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height * 0.6, // 设置容器高度
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    isReleases
                        ? Icons.music_note_outlined
                        : Icons.favorite_border,
                    size: 80.w,
                    color: Colors.white.withValues(alpha: 0.5),
                  ),

                  SizedBox(height: 20.h),

                  Text(
                    isReleases ? 'No releases yet' : 'No favorites yet',
                    style: TextStyle(
                      fontSize: 18.sp,
                      color: Colors.white.withValues(alpha: 0.7),
                      fontFamily: 'Poppins',
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
